
const coBody = require('co-body');
const log4js = require('log4js');
const logger = log4js.getLogger('jxData');


const dataSeq = [
    {
        name: 'pm2_5', getVal(buff) {
            return buff.readUInt32BE();
        }
    },
    {
        name: 'pm10', getVal(buff) {
            return buff.readUInt32BE();
        }
    },
    {
        name: 'noics', getVal(buff) {
            return buff.readUInt32BE() / 10;
        }
    },
    {
        name: 'temperature', getVal(buff) {
            return buff.readInt32BE() / 10;
        }
    },
    {
        name: 'humidity', getVal(buff) {
            return buff.readUInt32BE() / 10;
        }
    },
    {
        name: 'windDirection', getVal(buff) {
            return buff.readUInt32BE();
        }
    },
    {
        name: 'windSpeed', getVal(buff) {
            return buff.readUInt32BE() / 10;
        }
    },
    {
        name: 'atmos', getVal(buff) {
            return buff.readUInt32BE() / 1000;
        }
    },
    {
        name: 'tsp', getVal(buff) {
            return buff.readUInt32BE();
        }
    },
];


module.exports = function (opts) {
    return async function (ctx, next) {
        let data = await coBody.text(ctx.req);;
        try {
            let buffer = Buffer.from(data, "hex");
            let ret = {
                frame: buffer.readUInt16BE(),
                version: buffer.readUInt8(2),
                device: buffer.slice(3, 9).toString("hex"),
                session: buffer.readUInt32BE(9),
                command: buffer.readUInt8(13),
                dataLength: buffer.readUInt16BE(14),

                detail: {
                    _offset: 16
                }
            };

            let offset = ret.detail._offset;
            for (let i = 0; i < ret.dataLength / 4; i++) {
                if (i < dataSeq.length) {
                    let dataS = dataSeq[i];
                    ret.detail[dataS.name] = dataS.getVal(buffer.slice(offset, offset + 4));
                }
                else {
                    ret.detail[`ext${i - dataSeq.length}`] = buffer.readUInt32BE(offset);
                }
                offset += 4;
            }

            ctx.req.JXData = ret;
        }
        catch (e) {
            logger.error(e);
        }
        next();
    }
};